/**
 * @Author:  renyc
 * @Date: 2023年2月9日10:14:55
 */
'use strict';

// import * as Cesium from "cesium/Cesium";
import SourceType from "../../type/SourceType";
import {SourceEventType} from "../../../event/EventType";
import GeoJsonProvider from "../../provider/vector/GeoJsonProvider";
import FeatureSource from "./FeatureSource";

// GEOJSON_OPTS = {
//     SOUCE_OPTS,

//     url : http://host:port/service/data.json
// }
class GeoJsonSource extends FeatureSource {

    constructor(name, options){

        if(!options){
            throw new Error('GeoJsonSource: options无效');
        }
        if(!options.url){
            throw new Error('GeoJsonSource: url为空');
        }

        super(name, options);
        
        this._type = SourceType.GEOJSON;
        this._provider = new GeoJsonProvider();

        // this._url = options.url;

        // this._json = undefined;     //fetch结果的json数据
        // /**
        //  *_delegate的值为Promise类型，具体为Promise.<GeoJsonSource>类型
        //  */
        // //this._delegate = Cesium.GeoJsonDataSource.load(this._url, options);

        // this._delegate = null;
        // this._cesiumGeoJsonDataSource = new Cesium.GeoJsonDataSource(name);
    }

    /**
     * 获取Json数据
     */
    get json(){
        return this._json;
    }

    /**
     * 返回内部delegate属性
     */
    get delegate(){
        return this._delegate;
    }

    /**
     * @Override
     */
    fetch(){
        let that = this;
        fetch(this._url).then(resp=>{
            return resp.json();
        })
        .then(json=>{
            that._json = json;
        
            that._fire(SourceEventType.FETCHED, { 
                json : json,            
                source : that,
                // format : DataFormat.GEOJSON,
                // datasetName : typeName
            });

            // that._delegate = that._cesiumGeoJsonDataSource.load(json);
        
            // that._fire(SourceEventType.FETCHED, { 
            //     json : json,
            //     data: that._delegate,                
            //     source : that,
            //     // format : DataFormat.GEOJSON,
            //     // datasetName : typeName
            // });
        }); 
    }


    /**
     * 清空Source
     * @override
     */
    cleanup(){
        if(this._delegate){
            this._delegate.then(dataSource=>{
                dataSource.entities.removeAll();
            })
        }
    }
}

export default GeoJsonSource;